package net.lcheng.shop.Controller;

import com.alibaba.fastjson.JSON;
import net.lcheng.model.OOrder;
import net.lcheng.model.OOrderItem;
import net.lcheng.model.User;
import net.lcheng.service.OOrderItemService;
import net.lcheng.service.ShoppingService;
import net.lcheng.service.TradeManageService;
import net.lcheng.service.UserService;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.utils.Oorder2OrderModel;
import net.lcheng.vo.OrderModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Created by LV on 2016/7/22.
 */
@Controller
public class UserOrderManageController {

    @Autowired
    private UserService userService;
    @Autowired
    private TradeManageService tradeManageService;
    @Autowired
    private OOrderItemService orderItemService;
    @Autowired
    private ShoppingService shoppingService;
    /**
     * 获取指定店铺的所有订单
     * @param model 模型
     * @param shopId 店铺Id
     * @return String
     */
    @RequestMapping(value = "/userOrder/getAllOrdersByShopId",method = RequestMethod.GET)
    public String getAllOrdersByShopId(Model model, @RequestParam("sid") int shopId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            /**获取当前用户*/
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSON.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            if (user!=null){
                //获取所有退单
               List<OOrder> orderList=tradeManageService.getAllOrders(shopId,user.getUserId());
                //转换对象
                List<OrderModel> orderModelList= Oorder2OrderModel.getOorder2OrderModel(orderList);
                model.addAttribute("orderModelList",orderModelList);
                model.addAttribute("shopId",shopId);
                return "/user_order/all_order";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 获取指定店铺和订单状态的所有订单
     * @param model 模型
     * @param shopId 店铺Id
     * @param status 订单状态
     * @return String
     */
    @RequestMapping(value = "/userOrder/getAllOrdersByStatus",method = RequestMethod.GET)
    public String getAllOrdersByStatus(Model model,@RequestParam("sid") int shopId,@RequestParam("status") int status){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
                /**获取当前用户*/
            Session session = currentUser.getSession();
            CurrentUserModel currentUserModel = JSON.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
            if (user!=null){
                //获取所有退单
                List<OOrder> orderList=tradeManageService.getAllOrders(shopId,user.getUserId(),status);
                //转换对象
                List<OrderModel> orderModelList= Oorder2OrderModel.getOorder2OrderModel(orderList);
                model.addAttribute("orderModelList",orderModelList);
                model.addAttribute("orderStatus",status);
                model.addAttribute("shopId",shopId);
                return "/user_order/all_order_status";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 买家取消订单
     * @param orderId 要取消的订单Id
     * @return String
     */
    @RequestMapping(value = "/userOrder/cancelOrder",method = RequestMethod.GET)
    public String cancelOrder(@RequestParam("oid") String orderId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (orderId!=null&&!orderId.equals("")){
                //获取订单信息
                OOrder order=tradeManageService.getOrderByPrimaryKey(orderId);
                order.setOrderStatus(-1);//订单的状态为取消状态
                order.setOrderCancelDescription("买家主动取消");
                order.setModifyOn(new Date());
                int status=tradeManageService.cancelOrderByBuyer(order);

                if (status>0)
                    return "redirect:/userOrder/getAllOrdersByShopId?sid="+order.getWxShopShopId();
                else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }
    /**
     * 获取订单的信息
     * @param model 模型
     * @param orderId 订单Id
     * @return String
     */
    @RequestMapping(value = "/userOrder/getOrderInformation",method = RequestMethod.GET)
    public String getOrderInformation(Model model, @RequestParam("oid") String orderId, HttpServletRequest request){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (orderId!=null){
                //查看订单信息
                OOrder order=tradeManageService.getOrderByPrimaryKey(orderId);
                //转换对象
                if (order!=null) {
                    OrderModel orderModel = Oorder2OrderModel.getOorder2OrderModel(order);
                    model.addAttribute("orderModel", orderModel);
                    //获取从哪个页面过来的url
                    String url = request.getHeader("referer");
                    //订单状态

                    int orderStatus = order.getOrderStatus();
                    //由不同的订单状态到不同的页面
                    switch (orderStatus) {
                        case 0:
                            return "/user_order/not_payment_order_infor";//等待付款
                        case 1:
                            return "/user_order/have_payment_order_infor";//已付款
                        case 2:
                            return "/user_order/receive_goods_order_infor";//等待收货
                        case 3:
                            return "redirect:" + url;
                        case -1:
                            return "redirect:" + url;
                    }
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 申请退款退货
     * @param model 模型
     * @param orderId 要退的订单主键
     * @return String
     */
    @RequestMapping(value = "/userOrder/applyRefund",method = RequestMethod.GET)
    public String applyRefund(Model model,@RequestParam("oid") String orderId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取需要退单的的信息，对于卖家未发货和已发货有不同的处理方式
            if (orderId!=null){
                OOrder order=tradeManageService.getOrderByPrimaryKey(orderId);
                if (order!=null){
                    int orderStatus=order.getOrderStatus();
                    //已付款未发货
                    if (orderStatus==1){
                        model.addAttribute("order",order);
                        return "/user_order/apply_refund_not_send_goods";

                        //已发货
                    }else if (orderStatus>=2){
                        OrderModel orderModel=Oorder2OrderModel.getOorder2OrderModel(order);
                        model.addAttribute("orderModel",orderModel);
                        return "/user_order/apply_refund_have_send_goods1";
                    }else
                        return "redirect:/error";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 申请退货（申请退货，一次只能申请退一个订单子商品）
     * @param model 模型
     * @param itemId 订单子商品主键
     * @return String
     */
    @RequestMapping(value = "/userOrder/applyRefundGoods",method = RequestMethod.GET)
    public String applyRefundGoods(Model model,@RequestParam("itemId") String itemId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (itemId!=null){
                OOrderItem orderItem=orderItemService.getOOrderItemByPrimaryKey(itemId);
                if (orderItem!=null) {
                    //获取该子项的订单信息
                    OOrder order=tradeManageService.getOrderByPrimaryKey(orderItem.getoOrderOrderId());
                    model.addAttribute("order",order);
                    model.addAttribute("orderItem", orderItem);
                    return "/user_order/apply_refund_have_send_goods2";
                }
                return "redirect:/error";
            }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 卖家未发货的退单申请
     * @param orderId 要退的订单Id
     * @param reason 退单理由
     * @param cause 退单原因
     * @return String
     */
    @RequestMapping(value = "/userOrder/applyRefundNoGoods",method = RequestMethod.POST)
    public String applyRefundNoGoods(String orderId,String reason,String cause){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (orderId!=null){
                //获取订单信息
                OOrder order=tradeManageService.getOrderByPrimaryKey(orderId);
                if (order!=null){

                    int status=shoppingService.refundMoney(orderId,reason,cause);
                    if (status>0)
                         return "redirect:/userOrder/getAllOrdersByShopId?sid="+order.getWxShopShopId();
                    else
                        return "redirect:/error";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 卖家已发货的订单申请
     * @param itemId 要退的订单的子商品主键
     * @param reason 退货理由
     * @param cause 退货原因
     * @return String
     */
    @RequestMapping(value = "/userOrder/applyRefundHaveGoods",method = RequestMethod.POST)
    public String applyRefundHaveGoods(String itemId,String reason,String cause){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (itemId!=null){
                //获取订单子商品信息
                OOrderItem orderItem=orderItemService.getOOrderItemByPrimaryKey(itemId);

                if (orderItem!=null) {
                    //获取订单信息
                    OOrder order = tradeManageService.getOrderByPrimaryKey(orderItem.getoOrderOrderId());
                    if (order != null) {
                        //执行退单方法
                        int status=shoppingService.refundGoodsAndMoney(itemId,reason,cause);

                        if (status>0)
                            return "redirect:/userOrder/applyRefund?oid=" + order.getOrderId();
                        else
                            return "redirect:/error";
                    }
                    return "redirect:/error";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 买家确认收货
     * @param orderId 确认收货的订单Id
     * @return String
     */
    @RequestMapping(value = "/userOrder/confirmReceiveGoods",method = RequestMethod.GET)
    public String confirmReceiveGoods(@RequestParam("oid") String orderId){
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取订单信息
            OOrder order=tradeManageService.getOrderByPrimaryKey(orderId);
            //将订单的状态改为已完成
            order.setOrderStatus(3);
            order.setGoodsGetTime(new Date());
            int status=shoppingService.confirmReceiveGoods(order);
            if (status>0)
                return "redirect:/userOrder/getAllOrdersByShopId?sid="+order.getWxShopShopId();
            else
                return "redirect:/error";
        }
        return "redirect:/login";
    }
}

